package com.shiyanlou.upms.system.controller;

import com.shiyanlou.upms.common.domain.Tree;
import com.shiyanlou.upms.common.utils.MD5Utils;
import com.shiyanlou.upms.common.utils.R;
import com.shiyanlou.upms.common.utils.RandomValidateCodeUtil;
import com.shiyanlou.upms.common.utils.ShiroUtils;
import com.shiyanlou.upms.system.domain.UpmsPermission;
import com.shiyanlou.upms.system.domain.UpmsUser;
import com.shiyanlou.upms.system.service.UpmsPermissionService;
import com.shiyanlou.upms.system.service.UpmsUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 登入相关的控制器
 */
@Controller
public class LoginController {

    // 注入对象
    @Autowired
    private UpmsPermissionService upmsPermissionService;

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String login(Model model) {
        //在登录功能中，Model可以用来封装用户输入的用户名和密码，并将其传递给业务逻辑层进行验证和处理。
        return "login";
    }

    /**
     * 验证码图片
     */
    @GetMapping("/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        RandomValidateCodeUtil validateCodeUtil = new RandomValidateCodeUtil();
        validateCodeUtil.getRandcode(request, response);
    }

    @Autowired
    private UpmsUserService upmsUserService;


    @PostMapping("/login")
    @ResponseBody
    public R ajaxLogin(String username, String password, String verify, HttpServletRequest request) {
        // 检验验证码
        try {
            String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return R.error("请输入验证码！");
            }
            if(!random.equalsIgnoreCase(verify)) {
                return R.error("验证码不正确！");
            }
        } catch (Exception e) {
            return R.error("验证码校验失败！");
        }
        UpmsUser user = upmsUserService.getUserByusername(username);
        if (user == null || user.getUserId() == null) {
            return R.error("用户不存在！");
        }
        // 密码加盐
        password += user.getSalt();
        // 验证用户信息
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return R.ok();
        } catch (LockedAccountException e) {
            return R.error("用户被锁定，请找管理员处理！");
        } catch (AuthenticationException e) {
            return R.error("用户名密码错误！");
        }
    }

    @GetMapping(value = {"", "/index"})
    String index(Model model) {
        // 获取用户资源
        List<Tree<UpmsPermission>> permissionDOList = upmsPermissionService.getTreeByUserId(ShiroUtils.getUserId());
        UpmsUser user = ShiroUtils.getUser();
        model.addAttribute("menus", permissionDOList);
        model.addAttribute("user", user);
        return "index";
    }

    @GetMapping("/logout")
    public String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @GetMapping("/main")
    public String main() {
        return "upms";
    }
}